package cn.net.autocode.platform.viewEngine;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring6.view.AbstractThymeleafView;

import java.util.HashMap;
import java.util.Map;

public class AutoCodeThymeleaf extends AbstractThymeleafView {

    private final String templateContent;

    private final static TemplateEngine viewTemplateEngine=new TemplateEngine();


    public AutoCodeThymeleaf(final String templateContent) {
        this.templateContent = templateContent;
    }


    public void render(final Map<String, ?> model, final HttpServletRequest request, final HttpServletResponse response)
            throws Exception {
        renderFragment(model, response);
    }


    protected void renderFragment(final Map<String, ?> model,final HttpServletResponse response)
            throws Exception {

        Context context = new Context();

        final Map<String, Object> mergedModel = new HashMap<>(30);
        if (model != null) {
            mergedModel.putAll(model);
        }
        context.setVariables(mergedModel);
        response.setCharacterEncoding("UTF-8");

        response.getWriter().write(viewTemplateEngine.process(templateContent, context));
        response.getWriter().flush();

    }



}